package com.jyt.peripheral.print

import android.app.Activity
import android.app.AlertDialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import com.jyt.peripheral.R
import com.jyt.peripheral.print.PrintManager.Companion.toast
import net.posprinter.posprinterface.IMyBinder
import net.posprinter.posprinterface.ProcessData
import net.posprinter.posprinterface.TaskCallback
import net.posprinter.service.PosprinterService
import net.posprinter.utils.BitmapToByteData
import net.posprinter.utils.DataForSendToPrinterTSC
import net.posprinter.utils.PosPrinterDev


/**
 * @author 陈聪
 * date 2021/4/7:14:03
 * usb打印
 */
class USBprinter(var context: Context) : BasePrinter() {

    companion object {
        var ISCONNECT = false
        var adrress: String? = null
        var myBinder: IMyBinder? = null
    }
    var mSerconnection: ServiceConnection? = null

    init {
        mSerconnection =  object : ServiceConnection {
                override fun onServiceConnected(
                    name: ComponentName,
                    service: IBinder
                ) {
                    myBinder = service as IMyBinder
                    Log.e("myBinder", "connect")
                }

                override fun onServiceDisconnected(name: ComponentName) {
                    Log.e("myBinder", "disconnect")
                }
            }
        init()
    }

    override fun hadConnect(): Boolean {
        return ISCONNECT
    }

    override fun init() {
        //bind service，get imyBinder
        val intent = Intent(context, PosprinterService::class.java)
        context.bindService(intent, mSerconnection!!, Activity.BIND_AUTO_CREATE)
        connectUSB()
    }

    /**
     * 进行标签打印
     */
    override fun startPrint(info: PrintInfo?,callBack:((Boolean)->(Unit))?):Boolean {
        //需将信息进行转换
        if(info?.printdata!=null){
            if (ISCONNECT) {
                printOrderInfo(info.printdata as ArrayList<String>, null, object : TaskCallback {
                    override fun OnSucceed() {
                        toast("发送成功")
                        callBack?.invoke(true)
                    }

                    override fun OnFailed() {
                        callBack?.invoke(false)
                        toast("发送失败")
                    }
                })
            } else {
                connectUSB()
            }
        }else{
            toast("打印信息有误")
        }
        return true
    }

    /**
     * 连接usb
     */
    fun connectUSB() {
        if (adrress.isNullOrEmpty()) {
            usbPortSelect()
            return
        }
        val usbAddress: String? = adrress
        if (usbAddress == null || usbAddress == "") {
            toast("连接断开")
        } else {
            toast("正在进行USB打印连接")
            myBinder?.ConnectUsbPort(
                context,
                usbAddress,
                object : TaskCallback {
                    override fun OnSucceed() {
                        ISCONNECT = true
                        toast("USB打印连接成功")
                        PrintManager.printCaches()
                    }

                    override fun OnFailed() {
                        ISCONNECT = false
                        toast("USB打印连接断开")
                    }
                })
        }
    }

    var dialogView3: View? = null
    private var tv_usb: TextView? = null
    private var usbList: List<String>? = null
    private var usblist: kotlin.collections.MutableList<kotlin.String?>? = null
    private var lv_usb: ListView? = null
    private var adapter3: ArrayAdapter<String>? = null

    /**
     * uSB连接
     */
    fun usbPortSelect() {
        if (dialogView3 != null && dialogView3?.isShown!!) {
            return
        }
        val inflater = LayoutInflater.from(context)
        dialogView3 = inflater.inflate(R.layout.usb_link, null)
        tv_usb = dialogView3?.findViewById(R.id.textView1) as TextView
        lv_usb = dialogView3?.findViewById(R.id.listView1) as ListView
        usbList = PosPrinterDev.GetUsbPathNames(context)
        if (usbList == null) {
            usbList = java.util.ArrayList<String>()
        }
        if (usbList?.size == 0) {
            tv_usb?.text = "未找到正在使用的usb设备，请连接后再试"
        } else {
            tv_usb?.text = "请选择连接的usb打印机端口"
        }
        adapter3 = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, usbList!!)
        lv_usb?.adapter = adapter3
        val dialog: AlertDialog = AlertDialog.Builder(context)
            .setView(dialogView3).create()
        dialog.show()
        setUsbLisener(dialog)
    }

    fun setUsbLisener(dialog: AlertDialog) {
        lv_usb?.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
            adrress = usbList?.get(i)!!
            dialog.cancel()
            connectUSB()
            Log.e("usbDev: ", adrress ?: "")
        }
    }


    fun printText(str: String?, taskCallback: TaskCallback?) {
        myBinder?.WriteSendData(
            taskCallback,
            ProcessData {
                val list: MutableList<ByteArray> =
                    java.util.ArrayList()
                //设置标签纸大小
                list.add(DataForSendToPrinterTSC.sizeBymm(50.0, 30.0))
                //设置间隙
                list.add(DataForSendToPrinterTSC.gapBymm(2.0, 0.0))
                //清除缓存
                list.add(DataForSendToPrinterTSC.cls())
                //设置方向
                list.add(DataForSendToPrinterTSC.direction(0))
                //线条
                //                    list.add(DataForSendToPrinterTSC.bar(10,10,200,3));
                //条码
                //                    list.add(DataForSendToPrinterTSC.barCode(10,15,"128",100,1,0,2,2,"abcdef12345"));
                //文本
                list.add(DataForSendToPrinterTSC.text(10, 30, "TSS24.BF2", 0, 1, 1, str))
                //打印
                list.add(DataForSendToPrinterTSC.print(1))
                list
            })
    }


    fun printbitmap(
        bitmap1: Bitmap?,
        taskCallback: TaskCallback?
    ) {
        myBinder?.WriteSendData(
            taskCallback,
            ProcessData {
                val list: MutableList<ByteArray> =
                    java.util.ArrayList()
                //设置标签纸大小
                list.add(DataForSendToPrinterTSC.sizeBymm(50.0, 30.0))
                //设置间隙
                list.add(DataForSendToPrinterTSC.gapBymm(2.0, 0.0))
                //清除缓存
                list.add(DataForSendToPrinterTSC.cls())
                //文本
                list.add(DataForSendToPrinterTSC.text(10, 60, "TSS24.BF2", 0, 1, 1, "我是文本哈哈哈哈"))
                list.add(
                    DataForSendToPrinterTSC.bitmap(
                        10,
                        10,
                        0,
                        bitmap1,
                        BitmapToByteData.BmpType.Threshold
                    )
                )
                //具体参数值请参看编程手册
                list.add(
                    DataForSendToPrinterTSC.qrCode(
                        200,
                        30,
                        "M",
                        3,
                        "A",
                        0,
                        "M1",
                        "S3",
                        "123456789"
                    )
                )
                list.add(DataForSendToPrinterTSC.print(1))
                list
            })
    }

    fun printOrderInfo(
        strs: ArrayList<String>,
        bitmap1: Bitmap?,
        taskCallback: TaskCallback?
    ) {
        myBinder?.WriteSendData(taskCallback) {
            val list: MutableList<ByteArray> =
                java.util.ArrayList()
            //设置标签纸大小
            list.add(DataForSendToPrinterTSC.sizeBymm(60.0, 30.0))
            //设置间隙
            list.add(DataForSendToPrinterTSC.gapBymm(2.0, 0.0))
            //清除缓存
            list.add(DataForSendToPrinterTSC.cls())
            //文本
            var dy = 10
            var qr: String? = null
            for (item in strs) {
                if (item.contains("QRCODE===")) {
                    qr = item.split("===").toTypedArray()[1]
                } else {
                    list.add(DataForSendToPrinterTSC.text(20, dy, "TSS24.BF2", 0, 1, 1, item))
                    dy += 30
                }
            }
            if (bitmap1 != null) {
                list.add(
                    DataForSendToPrinterTSC.bitmap(
                        350,
                        30,
                        0,
                        bitmap1,
                        BitmapToByteData.BmpType.Threshold
                    )
                )
            }
            //具体参数值请参看编程手册
            if (!TextUtils.isEmpty(qr)) {
                list.add(DataForSendToPrinterTSC.qrCode(300, 100, "M", 6, "A", 0, "M1", "S3", qr))
            }
            list.add(DataForSendToPrinterTSC.print(1))
            list
        }
    }

    override fun close() {
        myBinder?.DisconnectCurrentPort(object :TaskCallback{
            override fun OnFailed() {
            }

            override fun OnSucceed() {
            }
        })
    }

}